<?php
namespace app\home\controller;
use think\Db;
use think\Session;
use think\Request;
use think\Cache;
class Weixin extends Index{
    private $appid = "wx87adcd7dbffd6a57";
    private $secret = "c8d14879a17b44f8d103b543d35f9b21";

    /**
     *授权登录
    */
    //curl模拟请求
    public  function http_curl($url,$type='get',$res='json',$arr=''){
        /*
        $url 请求的url
        $type 请求类型
        $res 返回数据类型
        $arr post请求参数
         */
        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if($type=='post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        if($res=='json'){
            return json_decode($output,true);
        }
    }


    /***
     * 微信授权登录,获取code
    */

    public function getCode(){
        //获取到code
        $appId = $this->appid;
        $redir_url = urlencode("http://www.pengjiujiu.top/home/weixin/getToken");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redir_url."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
//        header('location:'.$url);
        $this->redirect($url);
    }


    public function getToken(){
        $code = $_GET['code'];
        $appId = $this->appid;
        $secret = $this->secret;
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
        $res = $this->http_curl($url,"get");
        $touken = $res['access_token'];
        $openid = $res['openid'];
        $src = "https://api.weixin.qq.com/sns/userinfo?access_token=$touken&openid=$openid&lang=zh_CN";
        $row = $this->http_curl($src,"get");
        $openid = $row['openid'];
        $imgurl = $row['headimgurl'];
        $name = $row['nickname'];
	$sex = $row['sex'];
	$map['openid'] = "$openid";
        $rest = Db::table("users")->where($map)->find();
        if($rest==null){
            //到首页
  	   $this->view->assign("openid",$openid);
            $this->view->assign("nickname",$name);
            $this->view->assign("headimgurl",$imgurl);
            $this->view->assign("sex",$sex);
            return view();
        }else{
          $this->success("登录成功",url('home/index/index'),2);
        }
    }
    /***
    *微信获取access_token
     */
    public function accessToken(){
        $appid = $this->appid;
        $secret = $this->secret;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
        $row = $this->http_curl($url,"get");
        //获取到的access_token保存在缓存里面
        $token = $row['access_token'];
        //过期时间
        $time = time()+7000;
        session('access_token',$token);
        session('access_token_time',$time);
        return $token;
    }

    /***
    获取微信票据
     *
     */
    public function  getjsApiTicket(){
        if(session::get('jsapiticket_time')>time() && session::get('jsapiticket')){
            $jsapiticket = session::get('jsapiticket');
        }else {
            $token = $this->accessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $token . "&type=jsapi";
            $res = $this->http_curl($url, "get");
            $jsapiticket = $res['ticket'];
            $time = time() + 7000;
            session("jsapiticket", $jsapiticket);
            session("jsapiticket_time", $time);
            return $jsapiticket;
        }
    }

/***
随机生成随机码(默认16位)
 */
    public function getRandcode($num=16){
            $array = array(
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                '1','2','3','4','5','6','7','8','9','0'
            );
        $max = count($array);
        $key ="";
        $str ="";
        for($i=0;$i<=$num;$i++){
            $key = rand(0,$max-1);
            $str .= $array[$key];
        }
        return $str;
    }
    /**
     *微信分享给朋友
     *
    */
    public function shareWx(){
        //获取票据
        $jsapi_ticket = $this->getjsApiTicket();
        $appid = $this->appid;
        $time = time();
        $url='www.pengjiujiu.top';
        $str = $this->getRandcode();
        $signature = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$str."&timestamp=".$time."&url=".$url."";
        $signature = sha1($signature);
        $this->view->assign("appid",$appid);
        $this->view->assign("signature",$signature);
        $this->view->assign("time",$time);
        $this->view->assign("str",$str);
        return view();
    }

    /**
     *微信完善注册信息
    */
    public function wxRegister()
    {
        Request::instance()->post();
            $param = Request::instance()->post();
            $rand_str = _rand_str(4);
            $mobile = $param['mobile'];
            $pass_word = $param['user_pwd'];
            $re_pass = $param['user_pwd1'];
            $user_name = $param['user_name'];
            $openid = $param['openid'];
            $user_photo =$param['user_photo'];
            $user_sex = $param['user_sex'];
            $user_pwd = md5(md5($pass_word).$rand_str);

            if ($pass_word != $re_pass) {
                $this->error("两次密码不一致！", url("home/users/register"));
            }

            $data = [
                'user_name' => $user_name,
                'openid' => $openid,
                'user_photo' => $user_photo,
                'user_sex' => $user_sex,
                'user_pwd' => $user_pwd,
                'mobile' => $mobile,
                'user_no' => $rand_str,
                'user_time' => time()
            ];
            
            $register = $this->addUser($data);

            if ($register == false) {
                $this->error('该用户已经被注册！', url('home/users/register'));
            } else {
                return json($register);
            }

    }
    
public function addUser($data){

    $id = $data['openid'];
    $map['openid'] = "\'{$id}\'";
    $row = Db::table('users')->where($map)->select();
	
    if($row==null){
        return false;
    }else{
        $res = Db::table('users')->insert($data);
        if($res>0){
            return true;
        }else{
            return false;
        }
    }

}




}